//
//  MainViewController.swift
//  ZMWWeibo
//
//  Created by 张美文 on 16/1/4.
//  Copyright © 2016年 walter. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
//        tabBar.tintColor = UIColor.orangeColor()
        
        //添加子控制器
        addChildViewControllers()

        
    }
    /**
     监听加号按钮的点击
     注意：监听按钮的点击方法不能是私有方法
     */
    func composeBtnClick(){
        print(__FUNCTION__)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //添加加号按钮
        setupComposeBtn()
    }
    
    
    // MARK: - 内部控制方法
    private func setupComposeBtn()
    {
        tabBar.addSubview(composeBtn)
        let width = UIScreen.mainScreen().bounds.size.width / CGFloat((viewControllers?.count)!)
        let rect = CGRect(x: 0, y: 0, width: width, height: 49)
        
        composeBtn.frame = CGRectOffset(rect, 2*width, 0)
        
    }
    
    /**
     添加子控制器
     */
    private func addChildViewControllers() {
        //1.获取json文件路径
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)
        //2.通过文件路径创建NSData
        if let jsonPath = path {
            let jsonData = NSData(contentsOfFile: jsonPath)
            do{
                //处理异常
                //3.序列化json数据-->Array
                let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers)
                print(dictArr)
                
                for dict in dictArr as! [[String:String]]
                {
                    addChildViewController(dict["vcName"]!, title: dict["title"]!, imageNamed: dict["imageName"]!)
                    
                }
                
            }catch{
                //发生异常之后的代码
                //从本地加载控制器
                print(error)
                addChildViewController("HomeTableViewController", title: "首页", imageNamed: "tabbar_home")
                addChildViewController("MessageTableViewController", title: "消息", imageNamed: "tabbar_message_center")
                addChildViewController("NullViewController", title: "", imageNamed: "")
                addChildViewController("DiscoverTableViewController", title: "发现", imageNamed: "tabbar_discover")
                addChildViewController("ProfileTableViewController", title: "我的", imageNamed: "tabbar_profile")
                
            }
            
        }
    }
    
    /**
     初始化子控制器
     
     - parameter childController: 需要初始化的子控制器
     - parameter title:           子控制器的标题
     - parameter imageNamed:      子控制器的图片
     */
//    private func addChildViewController(childController: UIViewController, title:String, imageNamed:String) {
    private func addChildViewController(childControllerName: String, title:String, imageNamed:String) {

        //动态获取命名空间
        let name = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
//        print(name)
        
        //通过字符串转换为类
        let cls:AnyClass? = NSClassFromString(name + "." + childControllerName)
//        print(cls)
        
        //通过类创建对象
        //1.将AnyClass转换为指定的类型
        let vcClass = cls as! UIViewController.Type
        //2.通过class创建对象
        let vctr = vcClass.init()
        print(vctr)
        
        //
        vctr.tabBarItem.image = UIImage(named: imageNamed)
        vctr.tabBarItem.selectedImage = UIImage(named: imageNamed+"_highlighted")
        
        vctr.title = title
        
        let nav = UINavigationController()
        nav.addChildViewController(vctr)
        
        addChildViewController(nav)

    }
    
    // MARK: - 懒加载
    private lazy var composeBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //添加监听
        btn.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}



































































